function getParameterByName(name, url) {
    url = url || window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

var uroot = getParameterByName('uroot');

const urlParams = new URLSearchParams(window.location.search);
const root = urlParams.get('uroot');
const nowUname = sessionStorage.getItem("nowUname");

var uid = getParameterByName('uid');
const id = parseInt(uid, 10);

var name = getParameterByName('uname');

if (nowUname) {
    document.getElementById('currentUname').textContent = nowUname;
} else {
    console.warn('未获取到用户名信息');
    document.getElementById('currentUname').textContent = '游客';
}

if (uroot != 2 && uroot != 4 && uroot != 8) {
    alert('身份认证失败，请重新登录');
    window.location.href = 'login.html';
}

document.addEventListener('DOMContentLoaded', function () {

    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const todayFormatted = `${year}-${month}-${day}`;
    // ================= 日期初始化 =================
    // 设置默认日期为 2025 年 2 月
    const defaultStartDate = '2025-02-01';
    const defaultEndDate = todayFormatted;

    // 设置日期输入框的值
    document.getElementById('start-date').value = defaultStartDate;
    document.getElementById('end-date').value = defaultEndDate;

    // ================= 事件监听 =================
    // 使用唯一ID选择器
    document.getElementById('financial-query-btn').addEventListener('click', function () {
        // 保持原有逻辑
        const startDate = document.getElementById('start-date').value;
        const endDate = document.getElementById('end-date').value;

        if (!startDate || !endDate) {
            alert('请选择开始日期和结束日期');
            return;
        }

        fetchFinancialStats(startDate, endDate);
        fetchPendingBills();
    });

    // ================= 默认数据加载 =================
    // 使用 2025 年日期加载初始数据
    fetchFinancialStats(defaultStartDate, defaultEndDate);
    fetchPendingBills();

    // 初始化图表
    const incomeChart = echarts.init(document.getElementById('income-chart'));
    const expenseChart = echarts.init(document.getElementById('expense-chart'));
    const profitChart = echarts.init(document.getElementById('profit-chart'));

    // 公共配置
    const commonOption = {
        tooltip: {
            trigger: 'axis',
            formatter: params => {
                const date = params[0].name;
                const value = params[0].value;
                const seriesName = params[0].seriesName;
                const isPredict = date === '2025-03';
                return `
                <strong>${date}${isPredict ? '（预测）' : ''}</strong><br/>
                ${params[0].marker} ${seriesName}: ¥${Number(value).toLocaleString()}
            `;
            }
        },
        xAxis: {
            type: 'category',
            axisLabel: {
                color: '#666',
                rotate: 30  // 防止月份重叠
            }
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                color: '#666',
                formatter: value => `¥${Number(value).toLocaleString()}`
            }
        },
        series: [{
            type: 'line',
            smooth: true,
            lineStyle: {width: 3},
            label: {
                show: true,
                position: 'top',      // 默认顶部显示
                distance: 10,        // 标签与数据点间距
                backgroundColor: '#fff',
                borderColor: '#ddd',
                borderWidth: 1,
                padding: [5, 8],
                borderRadius: 4,
                formatter: ({value}) => `¥${Math.round(value).toLocaleString()}`,
                textStyle: {
                    color: '#333',
                    fontWeight: 'bold'
                }
            }
        }]
    };

    async function fetchMonthlyData() {
        const months = [
            {year: 2024, month: 11},
            {year: 2024, month: 12},
            {year: 2025, month: 1},
            {year: 2025, month: 2},
            {year: 2025, month: 3} // 添加三月份的数据
        ];

        const data = [];

        for (const m of months) {
            // 计算当月的第一天
            const start = new Date(m.year, m.month - 1, 2);

            // 计算当月的最后一天
            const end = new Date(m.year, m.month, 1); // m.month - 1 + 1 = m.month，表示下个月的第一天减去一天

            // 生成 URL 参数
            const startDateStr = start.toISOString().split('T')[0];
            const endDateStr = end.toISOString().split('T')[0];

            const response = await fetch(`/financialStats?startTime=${startDateStr}&endTime=${endDateStr}`);
            const {revenue, expenses} = await response.json();

            data.push({
                month: `${m.year}-${String(m.month).padStart(2, '0')}`,
                revenue,
                expenses,
                profit: revenue - expenses
            });
        }

        return data;
    }

    async function renderCharts() {
        const monthlyData = await fetchMonthlyData();

        // 确保 monthlyData 包含足够的数据
        if (monthlyData.length < 5) {
            console.error('monthlyData 数据不足，无法计算增长率');
            return;
        }

        // 提取 2025 年 2 月和 3 月的利润
        const febProfit = monthlyData[3].profit; // 2025-02
        const marProfit = monthlyData[4].profit; // 2025-03

        // 计算增长率
        const growthRate = (marProfit - febProfit) / febProfit;

        // 预测 2025 年 4 月的利润
        const predictAprilProfit = Math.round(marProfit * (1 + growthRate));

        // 预测收入和支出
        const febRevenue = monthlyData[3].revenue;
        const marRevenue = monthlyData[4].revenue;
        const revenueGrowthRate = (marRevenue - febRevenue) / febRevenue;
        const predictAprilRevenue = Math.round(marRevenue * (1 + revenueGrowthRate));

        const febExpenses = monthlyData[3].expenses;
        const marExpenses = monthlyData[4].expenses;
        const expensesGrowthRate = (marExpenses - febExpenses) / febExpenses;
        const predictAprilExpenses = Math.round(marExpenses * (1 + expensesGrowthRate));

        // 收入图表
        incomeChart.setOption({
            ...commonOption,
            title: {
                text: '收入趋势',
                subtext: '单位：人民币（元）',
                left: 'center'
            },
            xAxis: {
                type: 'category',
                data: [...monthlyData.map(d => d.month), '2025-04'],
                axisLabel: {
                    formatter: value => value === '2025-04' ? `${value}\n（预测）` : value
                }
            },
            series: [{
                ...commonOption.series[0],
                name: '月收入',
                data: [
                    ...monthlyData.map(d => d.revenue),
                    {
                        value: predictAprilRevenue,
                        itemStyle: {
                            color: '#2ecc71',
                            borderType: 'dashed'
                        },
                        label: {
                            formatter: `¥${predictAprilRevenue.toLocaleString()}\n（预测）`,
                            fontWeight: 'bold'
                        }
                    }
                ],
                itemStyle: {color: '#2ecc71'},
                label: {
                    ...commonOption.series[0].label,
                    position: (params) => {
                        return params.dataIndex === 0 ? 'right' :
                            params.dataIndex === monthlyData.length ? 'left' : 'top';
                    }
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {offset: 0, color: 'rgba(46,204,113,0.3)'},
                        {offset: 1, color: 'rgba(46,204,113,0.05)'}
                    ])
                }
            }]
        });

        // 支出图表
        expenseChart.setOption({
            ...commonOption,
            title: {
                text: '支出分析',
                subtext: '单位：人民币（元）',
                left: 'center'
            },
            xAxis: {
                type: 'category',
                data: [...monthlyData.map(d => d.month), '2025-04'],
                axisLabel: {
                    formatter: value => value === '2025-04' ? `${value}\n（预测）` : value
                }
            },
            series: [{
                ...commonOption.series[0],
                name: '月支出',
                data: [
                    ...monthlyData.map(d => d.expenses),
                    {
                        value: predictAprilExpenses,
                        itemStyle: {
                            color: '#e74c3c',
                            borderType: 'dashed'
                        },
                        label: {
                            formatter: `¥${predictAprilExpenses.toLocaleString()}\n（预测）`,
                            fontWeight: 'bold'
                        }
                    }
                ],
                itemStyle: {color: '#e74c3c'},
                label: {
                    ...commonOption.series[0].label,
                    position: 'bottom',
                    textStyle: {color: '#e74c3c'}
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {offset: 0, color: 'rgba(231,76,60,0.3)'},
                        {offset: 1, color: 'rgba(231,76,60,0.05)'}
                    ])
                }
            }]
        });

        // 利润预测图表
        profitChart.setOption({
            ...commonOption,
            title: {
                text: '利润预测',
                subtext: '2025-04为预测数据',
                left: 'center'
            },
            xAxis: {
                data: [...monthlyData.map(d => d.month), '2025-04'],
                axisLabel: {
                    formatter: value => value === '2025-04' ? `${value}\n（预测）` : value
                }
            },
            series: [{
                ...commonOption.series[0],
                name: '利润',
                data: [
                    ...monthlyData.map(d => Math.round(d.profit)),
                    {
                        value: predictAprilProfit,
                        itemStyle: {
                            color: '#3498db',
                            borderType: 'dashed'
                        },
                        label: {
                            formatter: `¥${predictAprilProfit.toLocaleString()}\n（预测）`,
                            fontWeight: 'bold'
                        }
                    }
                ],
                lineStyle: {
                    type: 'dotted',
                    dashOffset: 10
                }
            }]
        });
    }

// 在manage.js的DOMContentLoaded事件监听器中添加
    // 在DOMContentLoaded事件监听器中添加
    document.querySelectorAll('.menu-item').forEach(item => {
        item.addEventListener('click', function () {
            const targetClass = this.dataset.target;
            const target = document.querySelector(`.${targetClass}`);

            // 空值保护
            if (!target) {
                console.error(`Target element .${targetClass} not found`);
                return;
            }

            // 隐藏所有内容区域
            document.querySelectorAll('.content-area, .manage, .market-trend').forEach(el => {
                el.style.display = 'none';
            });

            // 显示目标内容区域
            target.style.display = 'block';

            // 更新激活状态
            document.querySelectorAll('.menu-item').forEach(menu => {
                menu.classList.toggle('active', menu === this);
            });
        });
    });
    document.querySelectorAll('.menu-item').forEach(item => {
        item.addEventListener('click', function () {
            const targetClass = this.dataset.target;
            const target = document.querySelector(`.${targetClass}`);

            // 隐藏所有内容区域
            document.querySelectorAll('.content-area, .manage, .market-trend').forEach(el => {
                el.style.display = 'none';
            });

            // 显示目标内容区域
            target.style.display = 'block';

            // 如果是市场趋向内容区域，初始化或重绘图表
            if (targetClass === 'market-trend') {
                setTimeout(() => {
                    window.dispatchEvent(new Event('resize'));
                }, 100);
            }

            // 更新激活状态
            document.querySelectorAll('.menu-item').forEach(menu => {
                menu.classList.toggle('active', menu === this);
            });
        });
    });

    // 获取返回主页按钮
    const returnHomeBtn = document.querySelector('.return-home-btn');
    // 添加点击事件
    returnHomeBtn.addEventListener('click', function () {
        // 获取 uroot 参数
        const uroot = getParameterByName('uroot');
        // 跳转到主页
        window.location.href = "main.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name)
    });

// 设置默认激活项
    document.querySelector('.menu-item[data-target="content-area"]').click();
    // 初始化执行
    renderCharts();
});

// ================= 核心功能函数 =================
// 获取财务统计数据
function fetchFinancialStats(startTime, endTime) {

    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const todayFormatted = `${year}-${month}-${day}`;


    fetch(`/financialStats?startTime=${startTime}&endTime=${endTime}`)
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    throw new Error(`请求失败: ${text}`);
                });
            }
            return response.json();
        })
        .then(data => {
            // 更新收入/支出显示
            document.querySelector('#total-revenue .value').textContent = `¥${data.revenue}`;
            document.querySelector('#total-expenses .value').textContent = `¥${data.expenses}`;

            // 计算并显示净利润
            const profit = data.revenue - data.expenses;
            document.querySelector('#total-profit .value').textContent = `¥${profit}`;

            // 获取对比数据
            fetchFebruaryData().then(februaryData => {
                updateMonthChange(data, februaryData);
            });
        })
        .catch(error => {
            console.error('财务数据请求错误:', error);
            alert(error.message);  // 显示错误信息给用户
        });
}

// 获取待处理账单
function fetchPendingBills() {
    fetch('/unallCar')
        .then(response => response.json())
        .then(data => {
            document.querySelector('#pending-bills .value').textContent = data;
        })
        .catch(error => console.error('账单请求错误:', error));
}

// ================= 数据对比逻辑 =================
// 获取二月对比数据
function fetchFebruaryData() {
    return new Promise((resolve, reject) => {
        // 固定对比 2025 年 2 月数据
        const febStart = '2025-01-01';
        const febEnd = '2025-01-31';  // 明确指定日期避免月末计算问题

        fetch(`/financialStats?startTime=${febStart}&endTime=${febEnd}`)
            .then(response => response.json())
            .then(data => resolve({
                revenue: data.revenue || 0,
                expenses: data.expenses || 0,
                profit: (data.revenue - data.expenses) || 0
            }))
            .catch(error => reject(error));
    });
}

// 更新百分比变化
function updateMonthChange(currentData, februaryData) {
    // 安全计算函数
    const safeCalc = (current, base) =>
        base === 0 ? 0 : ((current - base) / base * 100).toFixed(2);

    // 计算各项变化
    const revenueChange = safeCalc(currentData.revenue, februaryData.revenue);
    const expensesChange = safeCalc(currentData.expenses, februaryData.expenses);
    const profitChange = safeCalc(
        currentData.revenue - currentData.expenses,
        februaryData.profit
    );

    // 更新 DOM
    document.querySelectorAll('.change span').forEach((elem, index) => {
        const values = [revenueChange, expensesChange, profitChange];
        elem.textContent = `${values[index]}% 较上月`;
    });
}


// index.js
const config = {
    apis: {
        color: '/countColor',
        price: '/countPriceRange',
        brand: '/countBrandRatio',
        trend: '/countMonthlySales'
    },
    colors: {
        primary: '#5470c6',
        secondary: '#91cc75',
        gradient: ['#5470c6', '#91cc75']
    },
    refreshInterval: 15000
};

class Dashboard {
    constructor() {
        this.charts = {
            color: echarts.init(document.getElementById('colorChart')),
            price: echarts.init(document.getElementById('priceChart')),
            brand: echarts.init(document.getElementById('brandChart')),
            trend: echarts.init(document.getElementById('trendChart'))
        };
        this.init();
    }

    async init() {
        await this.loadData();
        this.bindEvents();
        setInterval(() => this.loadData(), config.refreshInterval);
    }

    async loadData() {
        try {
            const [colorData, priceData, brandData, trendData] = await Promise.all([
                this.fetchData(config.apis.color),
                this.fetchData(config.apis.price),
                this.fetchData(config.apis.brand),
                this.fetchData(config.apis.trend)
            ]);

            this.updateCharts({colorData, priceData, brandData, trendData});
            this.updateAnalysis(colorData, priceData, brandData, trendData);
        } catch (error) {
            console.error('数据加载失败:', error);
        }
    }

    async fetchData(url) {
        const res = await fetch(url);
        return res.json();
    }

    updateCharts(data) {
        this.charts.color.setOption(this.getColorOption(data.colorData));
        this.charts.price.setOption(this.getPriceOption(data.priceData));
        this.charts.brand.setOption(this.getBrandOption(data.brandData));
        this.charts.trend.setOption(this.getTrendOption(data.trendData));
    }

    // 颜色分布图配置
    getColorOption(data) {
        const total = data.reduce((sum, d) => sum + d.count, 0);
        return {
            title: {show: false},
            tooltip: {
                trigger: 'item',
                formatter: ({name, value, percent}) => `
              <div style="font-weight:500">${name}</div>
              <div>数量：${value}辆</div>
              <div>占比：${percent}%</div>
          `
            },
            legend: {
                orient: 'vertical',
                left: 'right',
                top: 'middle',
                formatter: name => {
                    const item = data.find(d => d.color === name);
                    return `${name} ${((item.count / total) * 100).toFixed(1)}%`;
                }
            },
            series: [{
                type: 'pie',
                radius: ['10%', '70%'],  // 调整半径范围
                center: ['35%', '50%'],
                roseType: 'radius',      // 新增玫瑰图模式
                itemStyle: {
                    borderRadius: 8,     // 圆角效果
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    formatter: '{b}\n{c}辆',
                    position: 'outer',
                    alignTo: 'edge',
                    margin: 20
                },
                data: data.map(d => ({
                    name: d.color,
                    value: d.count
                }))
            }]
        };
    }

    // 价格分布图配置
    getPriceOption(data) {
        return {
            yAxis: {
                type: 'category',
                data: data.map(d => d.price_range),
                axisLabel: {rotate: 0}
            },
            xAxis: {
                name: '车辆数量',
                max: data.reduce((max, d) => Math.max(max, d.count), 0) * 1.1 // 自动调整X轴范围
            },
            series: [{
                type: 'bar',
                data: data.map(d => d.count),
                label: {
                    show: true,
                    position: 'right',
                    formatter: '{@[1]}辆'
                },
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [ // 修改渐变方向
                        {offset: 0, color: config.colors.gradient[0]},
                        {offset: 1, color: config.colors.gradient[1]}
                    ])
                }
            }]
        };
    }

    // 品牌销售图配置
    getBrandOption(data) {
        return {
            dataset: {
                source: data.map(d => [
                    d.brand,  // 维度 0: 品牌名称
                    d.total,  // 维度 1: 总数量
                    d.sold,   // 维度 2: 已售数量
                    d.ratio   // 维度 3: 销售占比
                ]),
                dimensions: ['brand', 'total', 'sold', 'ratio']
            },
            tooltip: {
                trigger: 'axis',
                formatter: params => {
                    const d = params[0].data;
                    return `
                  <strong>${d[0]}</strong><br>
                  总车辆：${d[1]}辆<br>
                  已售：${d[2]}辆<br>
                  占比：${d[3]}%
              `;
                }
            },
            xAxis: {
                type: 'category',
                axisLabel: {
                    rotate: 45,       // 标签旋转45度
                    interval: 0,     // 强制显示所有标签
                    formatter: value =>
                        value.length > 4 ?
                            value.substr(0, 4) + '...' : value,  // 超长品牌名省略
                    margin: 15        // 标签与轴线间距
                },
                axisTick: {
                    alignWithLabel: true  // 刻度与标签对齐
                },
                data: data.map(d => d.brand)  // 直接绑定品牌字段
            },
            yAxis: [
                {
                    name: '销售占比(%)',
                    max: 100,
                    axisLabel: {
                        formatter: '{value}%',
                        margin: 10
                    }
                },
                {
                    name: '销售数量',
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}辆'
                    }
                }
            ],
            grid: {
                bottom: '30%'  // 增加底部空间
            },
            series: [
                {
                    type: 'bar',
                    yAxisIndex: 0,
                    encode: {x: 'brand', y: 'ratio'},
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{@[3]}%',  // 显示百分比
                        color: '#333'
                    },
                    // 修改品牌销售占比图的渐变色配置
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ // 修正此处API名称
                            {offset: 0, color: '#5470c6'},
                            {offset: 1, color: '#193c8f'}
                        ])
                    }
                },
                {
                    type: 'line',
                    yAxisIndex: 1,
                    encode: {x: 'brand', y: 'sold'},
                    symbolSize: 8,
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{@[2]}辆',  // 显示具体销量
                        color: '#ee6666'
                    },
                    lineStyle: {
                        width: 2,
                        type: 'dashed'
                    },
                    itemStyle: {
                        color: '#ee6666'
                    }
                }
            ]
        };
    }

    // 趋势图配置
    getTrendOption(data) {
        return {
            xAxis: {
                type: 'category',
                data: data.map(d => d.month),
                axisLabel: {
                    formatter: value => {
                        // 格式化显示为"2023年01月"
                        const [year, month] = value.split('-');
                        return `${year}年${month}月`;
                    }
                }
            },
            yAxis: {
                name: '销售数量（辆）',
                minInterval: 1 // 保证显示整数
            },
            tooltip: {
                trigger: 'axis',
                formatter: params => {
                    const [year, month] = params[0].name.split('-');
                    return `
                  ${year}年${month}月<br>
                  销售数量：${params[0].value}辆
              `;
                }
            },
            series: [{
                type: 'line',
                data: data.map(d => d.sales),
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{@[1]}辆' // 显示具体数值
                },
                itemStyle: {
                    color: '#5470c6'
                }
            }],
            dataZoom: [{
                type: 'slider',
                start: Math.max(0, (data.length - 12) / data.length * 100),
                end: 100
            }]
        };
    }

    updateAnalysis(colorData, priceData, brandData, trendData) {
        // 颜色分布分析
        if (colorData.length > 0) {
            const totalColor = colorData.reduce((sum, d) => sum + d.count, 0);
            let colorAnalysisHtml = '';
            colorData.forEach(d => {
                const ratio = (d.count / totalColor * 100).toFixed(1);
                if (d.count === Math.max(...colorData.map(item => item.count))) {
                    colorAnalysisHtml += `
            <strong>${d.color}色</strong>车辆是最受欢迎的颜色，占总销售的<strong>${ratio}%</strong>。
            建议在库存管理中优先考虑增加<strong>${d.color}色</strong>车辆的供应，以满足市场需求。<br>
          `;
                } else if (d.count === Math.min(...colorData.map(item => item.count))) {
                    colorAnalysisHtml += `
            <strong>${d.color}色</strong>车辆的销售量相对较低，仅占总销售的<strong>${ratio}%</strong>。
            可以考虑减少该颜色车辆的进货量，避免库存积压。<br>
          `;
                } else {
                    colorAnalysisHtml += `
            <strong>${d.color}色</strong>车辆的销售表现稳定，占总销售的<strong>${ratio}%</strong>。
            建议根据市场需求灵活调整库存。<br>
          `;
                }
            });
            document.getElementById('colorAnalysis').innerHTML = colorAnalysisHtml;
        }

        // 价格区间分布分析
        if (priceData.length > 0) {
            const totalSales = priceData.reduce((sum, d) => sum + d.count, 0);
            let priceAnalysisHtml = '';
            priceData.forEach(d => {
                const ratio = (d.count / totalSales * 100).toFixed(1);
                if (ratio >= 30) {
                    priceAnalysisHtml += `
            <strong>${d.price_range}</strong>价格区间的车辆市场需求旺盛，占总销售的<strong>${ratio}%</strong>。
            建议在采购计划中增加该价格区间的车辆，以满足消费者需求。<br>
          `;
                } else if (ratio < 30 && ratio >= 10) {
                    priceAnalysisHtml += `
            <strong>${d.price_range}</strong>价格区间的车辆销售情况良好，占总销售的<strong>${ratio}%</strong>。
            可以根据市场反馈适度调整该价格区间的车辆库存。<br>
          `;
                } else {
                    priceAnalysisHtml += `
            <strong>${d.price_range}</strong>价格区间的车辆销售相对较少，仅占总销售的<strong>${ratio}%</strong>。
            建议减少该价格区间的车辆进货，优化库存结构。<br>
          `;
                }
            });
            document.getElementById('priceAnalysis').innerHTML = priceAnalysisHtml;
        }

        // 品牌销售分析
        if (brandData.length > 0) {
            let brandAnalysisHtml = '';
            brandData.forEach(d => {
                if (d.ratio >= 30) {
                    brandAnalysisHtml += `
            <strong>${d.brand}</strong>品牌在市场上具有较强的竞争力，销售占比高达<strong>${d.ratio.toFixed(1)}%</strong>。
            建议加大该品牌的市场推广力度，进一步提升其市场份额。<br>
          `;
                } else if (d.ratio < 30 && d.ratio >= 20) {
                    brandAnalysisHtml += `
            <strong>${d.brand}</strong>品牌销售表现稳定，占比为<strong>${d.ratio.toFixed(1)}%</strong>。
            可以考虑维持当前的进货策略，同时关注市场动态。<br>
          `;
                } else {
                    brandAnalysisHtml += `
            <strong>${d.brand}</strong>品牌的市场表现相对较弱，占比为<strong>${d.ratio.toFixed(1)}%</strong>。
            建议分析其销售不佳的原因，并考虑调整营销策略或减少进货量。<br>
          `;
                }
            });
            document.getElementById('brandAnalysis').innerHTML = brandAnalysisHtml;
        }

        // 趋势分析
        if (trendData.length >= 2) {
            const currentMonth = trendData[trendData.length - 1];
            const previousMonth = trendData[trendData.length - 2];
            let trendAnalysisHtml = '';

            if (currentMonth.sales > previousMonth.sales) {
                const growthRate = ((currentMonth.sales - previousMonth.sales) / previousMonth.sales * 100).toFixed(1);
                trendAnalysisHtml += `
          与上月相比，本月销售数量增长了<strong>${growthRate}%</strong>，达到<strong>${currentMonth.sales}辆</strong>。
          这表明市场需求正在上升，建议提前准备库存以应对可能的销售高峰。<br>
        `;

                // 预测下月销售
                const predictedSales = Math.round(currentMonth.sales * (1 + growthRate / 100));
                trendAnalysisHtml += `
          根据当前增长趋势，预计下月销售数量约为<strong>${predictedSales}辆</strong>，建议适当增加进货量。
        `;
            } else if (currentMonth.sales < previousMonth.sales) {
                const declineRate = ((previousMonth.sales - currentMonth.sales) / previousMonth.sales * 100).toFixed(1);
                trendAnalysisHtml += `
          与上月相比，本月销售数量下降了<strong>${declineRate}%</strong>，为<strong>${currentMonth.sales}辆</strong>。
          这可能表明市场需求有所减弱，建议谨慎调整库存策略，避免过度进货。<br>
        `;

                // 预测下月销售
                const predictedSales = Math.round(currentMonth.sales * (1 - declineRate / 100));
                trendAnalysisHtml += `
          预计下月销售数量可能进一步下降至约<strong>${predictedSales}辆</strong>，建议根据实际情况灵活调整进货计划。
        `;
            } else {
                trendAnalysisHtml += `
          本月销售数量与上月持平，均为<strong>${currentMonth.sales}辆</strong>。
          市场需求目前较为稳定，建议维持当前库存策略。<br>
        `;

                // 预测下月销售
                const predictedSales = currentMonth.sales;
                trendAnalysisHtml += `
          预计下月销售数量将保持在约<strong>${predictedSales}辆</strong>，建议根据实际销售情况微调库存。
        `;
            }

            document.getElementById('trendAnalysis').innerHTML = trendAnalysisHtml;
        }
    }

    bindEvents() {
        window.addEventListener('resize', () => {
            Object.values(this.charts).forEach(chart => chart.resize());
        });
    }
}

document.querySelectorAll('.menu-item').forEach(item => {
    item.addEventListener('click', function () {
        const targetClass = this.dataset.target;
        const target = document.querySelector(`.${targetClass}`);

        // 隐藏所有内容区域
        document.querySelectorAll('.content-area, .manage, .market-trend').forEach(el => {
            el.style.display = 'none';
        });

        // 显示目标内容区域
        target.style.display = 'block';

        // 如果是市场趋向内容区域，初始化或重绘图表
        if (targetClass === 'market-trend') {
            setTimeout(() => {
                window.dispatchEvent(new Event('resize'));
            }, 100);
        }

        // 更新激活状态
        document.querySelectorAll('.menu-item').forEach(menu => {
            menu.classList.toggle('active', menu === this);
        });
    });
});


// 实例化 Dashboard 类
const dashboard = new Dashboard();

// 在DOMContentLoaded事件监听器中调用初始化
document.addEventListener('DOMContentLoaded', function () {
    // 初始化市场趋向图表
    dashboard.init();
});

function ccc() {
    window.location.href = "index.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name)
}

// 生成Word报告功能
async function generateWordReport() {
    // 获取所有需要的数据
    const [colorData, priceData, brandData, trendData] = await Promise.all([
        fetch(config.apis.color).then(r => r.json()),
        fetch(config.apis.price).then(r => r.json()),
        fetch(config.apis.brand).then(r => r.json()),
        fetch(config.apis.trend).then(r => r.json())
    ]);

    // 创建Word内容
    const htmlContent = `
    <html>
      <head>
        <meta charset="UTF-8">
        <style>
          table { border-collapse: collapse; width: 100%; margin:20px 0 }
          th, td { border: 1px solid #ddd; padding: 8px; text-align: left }
          th { background-color: #f2f2f2 }
        </style>
      </head>
      <body>
        <h2>智能销售分析报告</h2>
        
        <h3>销售趋势分析</h3>
        <p>${document.getElementById('trendAnalysis').innerText}</p>
        
        <h3>颜色分布分析</h3>
        <table>
          <tr><th>颜色</th><th>占比</th><th>建议</th></tr>
          ${colorData.map(d => {
        const ratio = (d.count / colorData.reduce((sum, item) => sum + item.count, 0)) * 100;
        if (ratio > 25) {
            return `
                <tr>
                    <td>${d.color}</td>
                    <td>${ratio.toFixed(1)}%</td>
                    <td>建议加大该颜色车辆的市场推广力度，进一步提升其销售表现。</td>
                </tr>
                `;
        } else if (ratio >= 20 && ratio <= 25) {
            return `
                <tr>
                    <td>${d.color}</td>
                    <td>${ratio.toFixed(1)}%</td>
                    <td>建议维持当前的销售策略，同时关注市场动态。</td>
                </tr>
                `;
        } else if (ratio < 20) {
            return `
                <tr>
                    <td>${d.color}</td>
                    <td>${ratio.toFixed(1)}%</td>
                    <td>建议分析该颜色车辆销售不佳的原因，并优化销售策略。</td>
                </tr>
                `;
        }
    }).join('')}
        </table>

        <h3>价格区间分析</h3>
        <table>
          <tr><th>价格区间</th><th>占比</th><th>建议</th></tr>
          ${priceData.map(d => {
        const ratio = (d.count / priceData.reduce((sum, item) => sum + item.count, 0)) * 100;
        if (ratio > 40) {
            return `
                <tr>
                    <td>${d.price_range}</td>
                    <td>${ratio.toFixed(1)}%</td>
                    <td>建议扩大该价格区间的车辆产品线，提供更多选择以满足消费者需求。</td>
                </tr>
                `;
        } else if (ratio >= 30 && ratio <= 40) {
            return `
                <tr>
                    <td>${d.price_range}</td>
                    <td>${ratio.toFixed(1)}%</td>
                    <td>建议维持当前的销售策略，同时关注市场动态。</td>
                </tr>
                `;
        } else {
            return `
                <tr>
                    <td>${d.price_range}</td>
                    <td>${ratio.toFixed(1)}%</td>
                    <td>建议分析该价格区间销售不佳的原因，并优化定价策略或促销活动。</td>
                </tr>
                `;
        }
    }).join('')}
        </table>

        <h3>品牌销售分析</h3>
        <table>
          <tr><th>品牌</th><th>销售占比</th><th>建议</th></tr>
          ${brandData.map(d => {
        if (d.ratio > 30) {
            return `
                <tr>
                    <td>${d.brand}</td>
                    <td>${d.ratio.toFixed(1)}%</td>
                    <td>建议加大该品牌的市场推广力度，进一步提升其市场份额。</td>
                </tr>
                `;
        } else if (d.ratio >= 20 && d.ratio <= 30) {
            return `
                <tr>
                    <td>${d.brand}</td>
                    <td>${d.ratio.toFixed(1)}%</td>
                    <td>建议维持当前的销售策略，同时关注市场动态。</td>
                </tr>
                `;
        } else {
            return `
                <tr>
                    <td>${d.brand}</td>
                    <td>${d.ratio.toFixed(1)}%</td>
                    <td>建议分析其销售不佳的原因，并优化品牌策略。</td>
                </tr>
                `;
        }
    }).join('')}
        </table>
      </body>
    </html>
  `;

    // 生成Word文件
    const blob = new Blob([htmlContent], {type: 'application/msword'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `销售报告_${new Date().toLocaleDateString()}.doc`;
    a.click();
    URL.revokeObjectURL(url);
}

// 绑定点击事件
document.getElementById('generateReport').addEventListener('click', generateWordReport);